<?php

namespace Cck\ArticlesSystem\Http\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Setting
 * @property-read SettingGroup $group
 * 
 * @property string $name
 * @property integer $group_id
 * @property string $display_name
 * @property string $value_type
 * @property string $value
 * @property-read mixed $casted_value 经过转换的value（根据value_type)
 */
class Setting extends Model
{
    protected $table = 'settings';

    public $timestamps = false;

    protected $fillable = [
        'name', 'group_id', 'display_name', 'value_type', 'value', 'form_type', 'form_optional', 'order'
    ];

    protected $casts = [
        'group_id' => 'integer',
    ];

    protected $appends = [
        'casted_value'
    ];

    public function getCastedValueAttribute()
    {
        if (is_null($this->attributes['value'] ?? null)) {
            return null;
        }

        if (is_null($this->attributes['value_type'] ?? null)) {
            return null;
        }

        return $this->castValue($this->attributes['value'], $this->attributes['value_type']);
    }

    public function castValue(string $value, string $valueType = 'string')
    {
        switch ($valueType) {
            case 'int':
            case 'integer':
                return (int)$value;
            case 'real':
            case 'float':
            case 'double':
                return $this->fromFloat($value);
            case 'decimal':
                return $this->asDecimal($value, 2);
            case 'string':
                return (string)$value;
            case 'bool':
            case 'boolean':
                return (bool)$value;
            case 'object':
                return $this->fromJson($value, true);
            case 'array':
            case 'json':
                return $this->fromJson($value);
            case 'collection':
                return new BaseCollection($this->fromJson($value));
            case 'date':
                return $this->asDate($value);
            case 'datetime':
            case 'custom_datetime':
                return $this->asDateTime($value);
            case 'timestamp':
                return $this->asTimestamp($value);
            default:
                return $value;
        }
    }

    public function group()
    {
        return $this->belongsTo(SettingGroup::class, 'group_id', 'id');
    }
}
